from configparser import ConfigParser
import os
import pandas as pd


class Reader():
    def read_ini(self, file_path):
        config = ConfigParser()
        result = {}
        if os.path.isfile(file_path):
            try:
                config.read(file_path, encoding='UTF-8')
                result = config._sections
                result = self.recursive_conversion(result)
                return result
            except OSError:
                raise ValueError("Read config file failed: %s" % OSError)
        return result

    def read_excel(self, file_path, **kwargs):
        data_dict = []
        try:
            data = pd.read_excel(file_path, engine='openpyxl', **kwargs)
            data_dict = {'data':data.to_dict('records')}
            self.recursive_conversion(data_dict)
        except Exception as E:
            print(E)
        finally:
            return data_dict['data']

    def recursive_conversion(self, conv_dict):
        for k, v in conv_dict.items():
            try:
                if isinstance(v, str):
                    v = v.replace(' ', '').replace('\n', '')
                    if isinstance(eval(v),dict) or isinstance(eval(v),list):
                        v = eval(v)
                if isinstance(v, dict):
                    conv_dict[k] = self.recursive_conversion(v)
                elif isinstance(v, list):
                    v_new = []
                    for item in v:
                        if isinstance(item, dict):
                            item = self.recursive_conversion(item)
                        v_new.append(item)
                    conv_dict[k] = v_new
                else:
                    conv_dict[k] = v
            except:
                conv_dict[k] = v
        return conv_dict


if __name__ == '__main__':
    result = Reader().read_ini('../Conf/config.ini')
    print(result)
    # print(type(eval(result['exec_example'])))
    #
    # print(type(eval('''"{'qdd':123}" ''')))
    # result = Reader().read_ini('../Conf/config.ini')
    result = Reader().read_excel('../Testcase/default/testcase/sys_user_login.xlsx')
    print(result)
